<template>
  <div class="profile-container">
    <div class="profile-header">
      <h2>个人中心</h2>
      <p>管理您的个人信息和账户设置</p>
    </div>

    <el-row :gutter="20">
      <!-- 左侧个人信息卡片 -->
      <el-col :span="8">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
            </div>
          </template>
          <div class="profile-info">
            <div class="avatar-section">
              <el-upload
                class="avatar-uploader"
                action=""
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="handleAvatarUpload"
              >
                <img v-if="profileData.avatar" :src="`http://localhost:8080/api/users/avatar/${profileData.id}?t=${avatarTimestamp}`" class="avatar" />
                <el-avatar v-else :size="100" :src="defaultAvatar">{{ profileData.name }}</el-avatar>
                <div class="change-avatar-text">点击更换头像</div>
              </el-upload>
            </div>
            <div class="user-basic-info">
              <p><strong>用户名：</strong>{{ profileData.username }}</p>
              <p><strong>姓名：</strong>{{ profileData.name }}</p>
              <p><strong>部门：</strong>{{ profileData.department }}</p>
              <p><strong>角色：</strong>{{ profileData.role }}</p>
              <p><strong>状态：</strong>
                <el-tag :type="profileData.status === 1 ? 'success' : 'danger'">
                  {{ profileData.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </p>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧信息编辑区域 -->
      <el-col :span="16">
        <el-tabs v-model="activeTab" type="card">
          <!-- 基本信息编辑 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>编辑基本信息</span>
                </div>
              </template>
              <el-form
                :model="basicInfoForm"
                :rules="basicInfoRules"
                ref="basicInfoFormRef"
                label-width="100px"
              >
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="basicInfoForm.username" disabled />
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="basicInfoForm.name" />
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                  <el-input v-model="basicInfoForm.phone" />
                </el-form-item>
                <el-form-item label="部门" prop="department">
                  <el-input v-model="basicInfoForm.department" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updateBasicInfo">保存信息</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-tab-pane>

          <!-- 密码修改 -->
          <el-tab-pane label="修改密码" name="password">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>修改密码</span>
                </div>
              </template>
              <el-form
                :model="passwordForm"
                :rules="passwordRules"
                ref="passwordFormRef"
                label-width="100px"
              >
                <el-form-item label="当前密码" prop="currentPassword">
                  <el-input v-model="passwordForm.currentPassword" type="password" show-password />
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input v-model="passwordForm.newPassword" type="password" show-password />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updatePassword">修改密码</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../../utils/request'
import defaultAvatar from '../../assets/images/default-avatar.png'

// 当前激活的标签页
const activeTab = ref('basic')

// 个人信息数据
const profileData = ref({
  id: 0,
  username: '',
  name: '',
  phone: '',
  department: '',
  role: '',
  status: 1,
  avatar: ''
})

// 头像时间戳，用于避免缓存
const avatarTimestamp = ref(Date.now())

// 基本信息表单
const basicInfoForm = reactive({
  username: '',
  name: '',
  phone: '',
  department: ''
})

// 基本信息表单验证规则
const basicInfoRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ]
}

// 密码表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码表单验证规则
const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { 
      validator: (rule: any, value: string, callback: any) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 表单引用
const basicInfoFormRef = ref()
const passwordFormRef = ref()

// 获取当前用户信息
const getCurrentUser = async () => {
  try {
    // 使用新的安全接口获取当前用户信息
    const response = await request.get('/api/users/current')
    profileData.value = {
      ...profileData.value,
      ...response.data,
      username: response.data.username,
      name: response.data.name,
      phone: response.data.phone || '',
      department: response.data.department || '',
      role: response.data.role,
      status: response.data.status,
      avatar: response.data.avatar || ''
    }
    
    // 更新表单数据
    basicInfoForm.username = profileData.value.username
    basicInfoForm.name = profileData.value.name
    basicInfoForm.phone = profileData.value.phone
    basicInfoForm.department = profileData.value.department
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

// 头像上传前的检查
const beforeAvatarUpload = (file: any) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt6M = file.size / 1024 / 1024 < 6

  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt6M) {
    ElMessage.error(`头像图片大小不能超过 6MB，当前文件大小: ${(file.size / 1024 / 1024).toFixed(2)}MB!`)
    return false
  }
  return true
}


// 处理头像上传
const handleAvatarUpload = async (options: any) => {
  const { file } = options
  try {
    // 创建FormData对象
    const formData = new FormData()
    formData.append('avatar', file)
    
    // 上传头像文件
    const response = await request.post('/api/users/current/avatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    // 更新本地数据
    profileData.value.avatar = response.data.avatar
    // 更新头像时间戳以刷新显示
    avatarTimestamp.value = Date.now()
    ElMessage.success('头像上传成功')
    
    // 更新localStorage中的用户信息，确保右上角头像更新
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      try {
        const userInfo = JSON.parse(userInfoStr)
        userInfo.avatar = response.data.avatar
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        
        // 触发storage事件，通知其他组件更新头像
        window.dispatchEvent(new StorageEvent('storage', {
          key: 'userInfo',
          oldValue: userInfoStr,
          newValue: JSON.stringify(userInfo)
        }))
      } catch (parseError) {
        console.error('Error parsing or updating user info:', parseError)
        ElMessage.error('头像信息更新失败')
      }
    }
  } catch (error: any) {
    console.error('头像上传失败:', error)
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
      ElMessage.error('文件上传超时，请选择较小的文件')
    } else if (error.message.includes('exceed')) {
      ElMessage.error('文件大小超过服务器限制，最大允许上传10MB的文件')
    } else {
      ElMessage.error('头像上传失败')
    }
  }
}

// 更新基本信息
const updateBasicInfo = async () => {
  if (!basicInfoFormRef.value) return
  
  await basicInfoFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 使用新的安全接口更新当前用户信息
        await request.put('/api/users/current', {
          ...basicInfoForm,
          avatar: profileData.value.avatar
        })
        
        // 更新本地存储的用户信息
        const userInfoStr = localStorage.getItem('userInfo')
        if (userInfoStr) {
          const userInfo = JSON.parse(userInfoStr)
          userInfo.name = basicInfoForm.name
          localStorage.setItem('userInfo', JSON.stringify(userInfo))
        }
        
        ElMessage.success('信息更新成功')
        getCurrentUser() // 重新获取用户信息
      } catch (error) {
        ElMessage.error('信息更新失败')
      }
    }
  })
}

// 修改密码
const updatePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 调用专门的修改密码接口
        await request.put(`/api/users/current/password`, {
          currentPassword: passwordForm.currentPassword,
          newPassword: passwordForm.newPassword
        })
        
        ElMessage.success('密码修改成功')
        
        // 重置表单
        passwordForm.currentPassword = ''
        passwordForm.newPassword = ''
        passwordForm.confirmPassword = ''
      } catch (error: any) {
        if (error.response && error.response.data && error.response.data.message) {
          ElMessage.error(error.response.data.message)
        } else {
          ElMessage.error('密码修改失败')
        }
      }
    }
  })
}

// 组件挂载时获取用户信息
onMounted(() => {
  getCurrentUser()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.profile-header {
  margin-bottom: 20px;
}

.profile-header h2 {
  color: #303133;
  margin-bottom: 10px;
}

.profile-header p {
  color: #606266;
  margin: 0;
}

.profile-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-weight: bold;
  color: #303133;
}

.profile-info {
  text-align: center;
}

.avatar-section {
  margin-bottom: 20px;
}

.avatar-uploader {
  display: inline-block;
  cursor: pointer;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

.change-avatar-text {
  margin-top: 10px;
  color: #409eff;
  font-size: 14px;
}

.user-basic-info {
  text-align: left;
  padding: 0 20px;
}

.user-basic-info p {
  margin: 10px 0;
  font-size: 14px;
}

:deep(.el-card) {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}
</style>